package com.jie.component.validation.aspect;

import com.jie.component.validation.annotion.Valid;
import com.jie.component.validation.core.ValidationExecutor;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**
 * @author jie
 * @version 1.0 2025-02-11
 */
@Aspect
@RequiredArgsConstructor
public class ValidationAspect {

    private final ValidationExecutor validationExecutor;

    // 匹配带有@Valid注解的方法
    @Pointcut("@annotation(com.jie.component.validation.annotion.Valid)")
    public void validMethod() {}

    @Before("validMethod()")
    public void validateParameters(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Parameter[] parameters = method.getParameters();
        Object[] args = joinPoint.getArgs();

        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            Object arg = args[i];

            if (parameter.isAnnotationPresent(Valid.class) && arg != null) {
                validationExecutor.validate(arg);
            }
        }
    }
}
